'''
Created on 18/gen/2010

@author: syn
'''
from ui.GladeBase import GladeBase
from utils.Environment import logger, envir
from data.models import Product, Book, ProductBooks, Author, Genre
from ui.treemodels import GenreListStore, AuthorListStore
from ui import AUTHOR, check_authorization, ADMIN
import gtk

NO_ENTITY = -1

class ManageBookstats(GladeBase):
    def __init__(self, author=None, top_component=None):
        logger.debug("UI: %s instance created" % self.__class__)
        GladeBase.__init__(self, 'manage_bookstats_frame', top_component)
        self.author = author
        self.genre = None
        
        self.genre_combobox.set_model(GenreListStore(Genre, Genre.query.all))
        self.author_combobox.set_model(AuthorListStore(Author, Author.query.all))
        
        if check_authorization(envir.get_user(), AUTHOR):
            self.author_combobox.set_sensitive(False)
        
        # Setting up product list
        self._load_to_gui()
    
    def _init_gui_components(self):
        """
        Intialize gui components as needed. This is useful in the contructor or 
        binded with particular actions (for instance, a "clear" button, or "new" button) 
        """
        self.book_list.clear()

    def _retrieve_components(self):
        """
        Retrieve all used gui components from builder. This method is called in the
        GladeBase constructor
        """
        self.get_from_builder('book_treeview')
        self.get_from_builder('book_list')     
        self.get_from_builder('genre_combobox')
        self.get_from_builder('author_combobox')       
    
    def _load_to_gui(self):
        self._init_gui_components()
        
        query = Product.query.join(ProductBooks, Book)
        if self.author:
            query = query.filter(Book.authors.contains(self.author))
        
        if self.genre:
            query = query.filter(Book.genres.contains(self.genre))

        sold = 0
        for pr in query.all():
            for o in pr.orders: sold += o.quantity 
            row = [pr.id, pr.name, pr.edition.name, len(pr.prints), 
                   round(pr.price, 2), sold, pr.quantity]
            self.book_list.append(row)
            
    # Signals
    def on_search_button_clicked(self, object, data=None):
        iter = self.genre_combobox.get_active_iter()
        if iter:
            self.genre = self.genre_combobox.get_model().get_entity(iter)
        else:
            self.genre = None
        
        iter = self.author_combobox.get_active_iter()
        if check_authorization(envir.get_user(), ADMIN):
            if iter:
                self.author = self.author_combobox.get_model().get_entity(iter)
            else:
                self.author = None
            
        self._load_to_gui()
    
    def on_reset_button_clicked(self, object, data=None):
        self.author_combobox.set_active(-1)
        self.genre_combobox.set_active(-1)